import { Component, OnInit } from '@angular/core';
// import { FormGroup, FormControl } from '@angular/forms';
import { FormBuilder, Validators, FormArray } from '@angular/forms';

@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile-editor.component.html',
  styleUrls: ['./profile-editor.component.scss']
})
export class ProfileEditorComponent implements OnInit {

	/** 使用FormGroup创建表单 **/
	/*
  profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    address: new FormGroup({
      street: new FormControl(''),
      city: new FormControl(''),
      state: new FormControl(''),
      zip: new FormControl('')
    })
  });
  */

  /** 使用FormBuilder创建表单 **/
  profileForm = this.fb.group({
  	firstName: ['', Validators.required],
  	lastName: [''],
  	address: this.fb.group({
  		street: [''],
  		city: [''],
  		state: [''],
  		zip: ['']
  	}),
  	aliases: this.fb.array([
  		this.fb.control('')
  	])
  });

  get aliases() {
	  return this.profileForm.get('aliases') as FormArray;
	}
  
  constructor(private fb: FormBuilder) { }
  

  ngOnInit() {
  }

  updateProfile() {
  	this.profileForm.patchValue({
  		firstName: 'Nancy',
      address: {
        street: '123 Drew Street'
      }
  	});
  }

	addAlias() {
		this.aliases.push(this.fb.control(''));
	}

  onSubmit() {
    // TODO: Use EventEmitter with form value
    console.log(this.profileForm.value);
  }

}
